<template>
<div style="font-size: 14px">
    <div style="background-color: #fafbfd;padding: 15px;margin-bottom: 15px;">
      筛选
    </div>
    <div style="padding: 0 15px;">
      <el-form ref="searchForm" :model="filters" label-suffix=":" :size="'medium'"
        @submit.native.prevent @keyup.enter.prevent>
        <el-form-item label="关键词">
          <el-col :span="3" style="margin-right: 15px;">
            <el-input v-model="filters.perName" clearable placeholder="请输入姓名" style="margin-left: 1rem;"></el-input>
          </el-col>
          <el-col :span="8" style="margin-left: 15px;">
            <el-input v-model="filters.perCard" clearable placeholder="请输入身份证号" style=""></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="企业相关">
          <el-col :span="8">
          <el-input v-model="filters.comName" clearable placeholder="请输入企业名称" style=""></el-input>
        </el-col>
        </el-form-item>
        <el-form-item label="工商相关">
          <el-col :span="3" style="margin-right: 15px;">
            <el-cascader ref="perTypeNameRef" 
            v-model="filters.perTypeNameCoye" 
            :options="perTypeNameList" 
            :props="{ expandTrigger: 'hover' }"
            clearable 
            placeholder="请选择人员类别"
             @change="handleChangeperTypeName" />
          </el-col>
          <el-col :span="3">
            <el-select ref="province" filterable clearable v-model="state_region.province" placeholder="注册属地: 省/直辖市"
              @change="provinceChange">
              <el-option v-for="item in region.province" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <template v-if="modelType !== 'talentPerson'">
              <el-select ref="city" v-model="state_region.city" placeholder="市" filterable clearable
                @change="cityChange">
                <el-option v-for="item in region.city" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </template>
          </el-col>
        </el-form-item>
        <el-form-item label="更多筛选">
          <div style="display: flex; align-items: center;">
            <div style="display: flex;align-items: center;">

              <el-popover placement="bottom" trigger="click" v-model="popoverVisible3" @show="handlePopoverShow3"
                style="margin: 0 10px;">
                <ul class="custom-select-list">
                  <li v-for="item in isPhoneList" :key="item.index"
                    :class="{ 'selected': filters.isNeedPhone === item.index }" @click="handleSelectpopover3(item)">
                    {{ item.name }}
                  </li>
                </ul>
                <el-button type="text" slot="reference" class="popover-trigger-btn">
                  <span :style="filters.isNeedPhone === '-1' ? '' : 'color:#409EFF'">{{ filters.isNeedPhone | isNeedPhoneFilter }}</span>
                  <i :class="popoverVisible3 ? 'el-icon-caret-top' : 'el-icon-caret-bottom'"
                    :style="filters.isNeedPhone === '-1' ? '' : 'color: #409EFF'" />
                </el-button>
              </el-popover>

            </div>
            <div style="margin-left: 50px;">
              <el-button type="info" size="mini" @click.native.prevent="refresh">重置</el-button>
            </div>
          </div>
        </el-form-item>
        <!-- <el-form-item label="已选条件">
          <div v-if="choiceList.length">
            <el-tag v-for="item in choiceList" :key="item.key" style="margin-right: 10px;">
            {{ item.Label }}
          </el-tag>
          </div>
          <div v-else style="color: #C0C4CC">暂未选择搜索条件</div>
        </el-form-item> -->
      </el-form>
    </div>
  </div>
</template>
<script>
import { getPerTypes } from '@/api/person'
import { getDistricts } from '@/api/company'
export default {
  name: 'SearchForm',
  props: {
    searchForm: { type: Object, default: null },
    modelType: { type: String, default: null },
  },
  filters:{
    isNeedPhoneFilter(status) {
      const statusMap = {
      '-1': '联系方式',
      '0': '有联系方式' ,
      '1':  '有手机' 
      }
      return statusMap[status]
    },
  },
  data() {
    return {
      popoverVisible3:false,
      isPhoneList: [
        { index: '-1', name: '全部' },
        { index: '0', name: '有联系方式' },
        { index: '1', name: '有手机' }
      ],
      region: {
        province: [],
        city: [],
        area: []
      },
      filters: null,
      state_region: null,
      choiceList:[],
      perTypeNameList:[],
    }
  },
  watch: {
    filters: {
      handler(newVal, oldVal) {
        let copyObj=Object.assign({},newVal);
          this.$emit('searchFormEmit', copyObj)
          this.setFilters(newVal)
        // 所有条件
        this.choiceList=[];
        for(let key in newVal){
          if((
            newVal[key]!=''
            &&newVal[key]!=undefined
            &&(newVal[key]!='0'||['isNeedPhone'].indexOf(key)>-1)
            &&newVal[key]!='-1'
          )
          ){
            //转换
            let selectValue=newVal[key];
            let label=selectValue;
            //选项
            let formFilter=this.searchForm.fields.filter(p=>p.name==key)[0];
            if(!formFilter){
              formFilter={};
            }
            if(['',].indexOf(key)>-1){
              label=formFilter.options.filter(p=>p.value==selectValue)[0].label;
            }else if(key=='distId'){
              let province=this.region.province.filter(p=>p.value==selectValue);
              if(province&&province.length>0){
                label=province[0].label;
              }else{
                let city=this.region.city.filter(p=>p.value==selectValue);
                if(city&&city.length>0){
                label=city[0].label;
                }
              }
            }
            else if(key=='isNeedPhone'){
              formFilter.label='联系电话';
              label=this.isPhoneList.filter(p=>p.index==selectValue)[0].name;
            }
            this.choiceList.push({
              Name:formFilter.label,
              Label:label,
              Value:selectValue,
              Key:key,
            });
          }
        }
      },
      deep: true
    },
    state_region: {
      handler(newVal, oldVal) {
        // 同步设置 store
        this.setRegion(newVal)
      },
      deep: true
    },
    'searchForm.reset': {
      handler(newVal) {
        if (newVal) {
          // 重置条件
          this.refresh()
        }
      },
      deep: true
    }
  },
  created() {
    this.getFilters()
    if (this.searchForm.region) {
      this.getRegion()
      this.getDistrictsList()
    }
    this.getPerType()
  },
  mounted(){
    document.addEventListener('click', this.handleOutsideClick) // 可选：监听全局点击事件，手动关闭下拉框。
  },
  methods: {
    handleOutsideClick(event){
        for (let key in this.$refs) {
        if (true||key.startsWith('child')) { //处理全部, 确保只处理我们关心的refs
          // 执行一些操作，例如调用子组件的方法或访问其数据
          try {
            let selectElement = this.$refs[key].$el;
            if (!selectElement.contains(event.target))
                this.$refs[key].blur()
          } catch (error) {
            console.log('handleOutsideClick-处理异常',error);
          }
          
        }
      }
    },
    handleSelectpopover3(item) {
      this.filters.isNeedPhone = item.index;
      this.popoverVisible3 = false; // 选择后关闭popover
      // 这里可以添加选择后的其他逻辑
    },
    getPerType() {
      const options = []
      this.loading = true
      getPerTypes().then((res) => {
        this.loading = false
        if (res.code === 200) {
          res.data.personTypes.forEach((item) => {
            const o = { value: item.name, label: item.name, children: [] }
            if (item.types.length > 0) {
              item.types.forEach(item2 => {
                o.children.push({ value: item2.name, label: item2.name })
              })
            } else {
              o.children = null
            }
            options.push(o)
          })
          this.perTypeNameList = options
          console.log('this.perTypeNameList', this.perTypeNameList)
        }
      })
    },
    // 以上
    handlePopoverShow3() {
      this.$nextTick(() => {
        this.$refs.selectRef3.focus()
        this.$refs.selectRef3.$el.querySelector('.el-input__inner').click()// 对于 Element UI 2.x，可能需要触发点击事件
      })
    },
    getFilters() {
      this.filters = this.$store.getters[this.modelType + '/getFilters']
    },
    setFilters(filters) {
      this.$store.dispatch(this.modelType + '/setFilters', filters)
    },
    resetFilters() {
      this.$store.dispatch(this.modelType + '/resetFilters')
      // 重置后重新获取
      this.getFilters()
    },
    getRegion() {
      this.state_region = this.$store.getters[this.modelType + '/getRegion']
      // 初始化地址
      if (this.state_region) {
        if (this.state_region.province !== '') {
          this.getDistrictsList(this.state_region.province, 'city')
        }

        if (this.state_region.city !== '') {
          this.getDistrictsList(this.state_region.city, 'area')
        }
      }
    },
    setRegion(filters) {
      this.$store.dispatch(this.modelType + '/setRegion', filters)
    },
    resetRegion() {
      this.$store.dispatch(this.modelType + '/resetRegion')
      this.region.city = []
      this.region.area = []
      // 重置后重新获取
      this.getRegion()
    },
    provinceChange(value) {
      if (this.modelType !== 'talentPerson') {
        this.getDistrictsList(value, 'city')
        this.region.city = []
        this.region.area = []
      }
      this.filters.distId = value
    },
    cityChange(value) {
      if (this.modelType === 'project') {
        this.getDistrictsList(value, 'area')
        this.region.area = []
      }

      this.filters.distId = value
    },
    areaChange(value) {
      this.filters.distId = value
    },
    getDistrictsList(distId = 0, node = 'province') {
      this.loading = true
        getDistricts({ distId: distId }).then((res) => {
          this.loading = false
          if (res.code === 200) {
            const options = []
            res.data.dists.forEach((item) => {
              const o = { value: item.DistId, label: item.DistName }
              options.push(o)
            })
            this.region[node] = options
          }
        })
    },
    refresh() {
      // 重置条件
      this.resetFilters()
      this.resetRegion()

      // 恢复重置条件
      this.searchForm.reset = false
    },
    handleChangeperTypeName(value) {
     this.perTypeNameCoye = value //展示看的
     this.filters.perTypeName = value[value.length - 1] // // 传名字给后台
    }
  }
}
</script>

<style scoped>
::v-deep .el-form-item{
  margin-bottom: 15px !important;
}
/* ul,li的样式 */
/* 自定义列表样式 */
.custom-select-list {
  list-style: none;
  margin: 0;
  padding: 5px 0;
  min-width: 120px;
}

.custom-select-list li {
  padding: 8px 16px;
  cursor: pointer;
  font-size: 14px;
  color: #606266;
}

.custom-select-list li:hover {
  background-color: #f5f7fa;
}

.custom-select-list li.selected {
  color: #409EFF;
  font-weight: 500;
  background-color: #ecf5ff;
}

/* 触发按钮样式 */
.popover-trigger-btn {
  color: #606266;
  font-weight: 700;
  padding: 0;
}

/* 调整popover样式 */
.custom-list-popover {
  padding: 0;
}

/* 结束ul>li */
::v-deep.no-wrap-select .el-select__tags {
  display: flex;
  flex-wrap: nowrap;
  overflow-x: auto;
  white-space: nowrap;
}

::v-deep.no-wrap-select .el-select__tags::-webkit-scrollbar {
  display: none; /* 隐藏滚动条 */
}

::v-deep.no-wrap-select .el-tag {
  flex-shrink: 0; /* 防止标签缩小 */
  margin-right: 6px;
}



/* 隐藏输入框 */
::v-deep .hidden-input-select .el-input__inner {
  display: none !important;
}

/* 调整下拉面板位置（可选） */
.hidden-input-select .el-select-dropdown {
  margin-top: -36px; /* 根据实际情况调整 */
}
::v-deep .el-tabs__item {
  height: 26px;
  line-height: 28px;
  font-size: 13px;
}

::v-deep .el-autocomplete-suggestion {
  /* width: auto !important; */
}

::v-deep .el-collapse-item__header {
  background-color: #fafbfd;
}

::v-deep .el-collapse-item__wrap {
  border-bottom: none;
}

/* 隐藏最后一个面板的图标 */
/* ::v-deep .el-collapse-item__arrow:last-child {
  display: none;
} */
::v-deep .el-tabs__nav-next {
  line-height: 26px;
}

::v-deep .el-tabs__nav-prev {
  line-height: 26px;
}

/* 提高下拉菜单的 */
::v-deep .custom-autocomplete .el-autocomplete-suggestion {
  color: red;
  width: 300px !important;
}
</style>
